<template>
  <div class="serial-container">
    <!-- 1. 用户交互按钮：触发串口权限请求 -->
    <button @click="requestSerialPort" :disabled="isConnecting || isConnected" class="connect-btn">
      {{ isConnecting ? '连接中...' : isConnected ? '已连接' : '连接串口设备' }}
    </button>

    <button @click="disconnectSerialPort" :disabled="!isConnected" class="disconnect-btn" v-if="isConnected"> 断开连接 </button>
  </div>
</template>

<script setup>
  import { ref, onUnmounted } from 'vue'
  import { SerialCommunicator } from '@/utils/serialSocket'
  import { websock } from '@/utils/websocket'

  const isConnecting = ref(false) // 是否正在连接中
  const isConnected = ref(false) // 是否已连接

  const requestSerialPort = async () => {
    try {
      isConnecting.value = true
      const result = await SerialCommunicator.connect(websock)
      isConnected.value = result
    } finally {
      isConnecting.value = false
    }
  }

  // 2. 断开串口连接
  const disconnectSerialPort = async () => {
    try {
      await SerialCommunicator.disconnect()
      isConnecting.value = false
      isConnected.value = false
    } catch (err) {
      console.error('断开错误', err)
    }
  }

  // 3. 组件卸载时自动断开连接（防止内存泄漏）
  onUnmounted(() => {
  if (isConnected.value) {
    disconnectSerialPort()
  }
  if (websock) {
    websock.close(1000, '组件卸载自动关闭')
  }
})
</script>

<style scoped>
  .serial-container {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  .connect-btn {
    padding: 8px 16px;
    background: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  .connect-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
  }
  .disconnect-btn {
    padding: 8px 16px;
    background: #f56c6c;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  .device-info {
    padding: 12px;
    border: 1px solid #eee;
    border-radius: 4px;
  }
  .error-message {
    color: #f56c6c;
    font-size: 14px;
  }
</style>
